/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.weiresearch.login;

import com.opensymphony.xwork2.ActionSupport;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author cgqhs
 */
public class SinaLoginAction extends ActionSupport {

    public String name;//sina user name
    public String password;//sina password

    //jsp属性
    public List<String> position0 = new ArrayList<String>();
    public List<String> position1 = new ArrayList<String>();
    public List<String> position4 = new ArrayList<String>();
    public List<String> position2 = new ArrayList<String>();
    public List<String> position3 = new ArrayList<String>();
    public List<String> position5 = new ArrayList<String>();

    public List<String> getPosition0() {
        return position0;
    }

    public void setPosition0(List<String> position0) {
        this.position0 = position0;
    }

    public List<String> getPosition1() {
        return position1;
    }

    public void setPosition1(List<String> position1) {
        this.position1 = position1;
    }

    public List<String> getPosition2() {
        return position2;
    }

    public void setPosition2(List<String> position2) {
        this.position2 = position2;
    }

    public List<String> getPosition3() {
        return position3;
    }

    public void setPosition3(List<String> position3) {
        this.position3 = position3;
    }

    public List<String> getPosition4() {
        return position4;
    }

    public void setPosition4(List<String> position4) {
        this.position4 = position4;
    }

    public List<String> getPosition5() {
        return position5;
    }

    public void setPosition5(List<String> position5) {
        this.position5 = position5;
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String execute() throws Exception {
        HttpSession session=ServletActionContext.getRequest().getSession();
        String path = ServletActionContext.getRequest().getContextPath();

        String url = "https://api.weibo.com/oauth2/access_token?client_id=3336068988&client_secret=76cb19ccdb02e1d6fefed609710fd98f&grant_type=password&username="+this.name+"&password="+this.password;
        String responseBody = this._sendHTTPPost(url);
        JSONObject response = new JSONObject(responseBody);
        if(response.has("errorDescription")){
            return ERROR;
        }else {
            if(response.has("access_token")&&response.has("uid")){
                session.setAttribute("access_token", response.getString("access_token"));
                session.setAttribute("sinaUid", response.getString("uid"));
                //
                String userName = "demo";
                String userPassword = "welcome1";
                String oauthUrl = "http://202.85.221.51:30080/Interestgraph/access_token?weiresearch_oauth_id="+userName+"&weiresearch_oauth_secret="+userPassword+"&grant_type=client_credentials";
                //String oauthUrl = "http://localhost:20080/graph/access_token?weiresearch_oauth_id="+userName+"&weiresearch_oauth_secret="+userPassword+"&grant_type=client_credentials";
                String responseText = this._sendHTTPGet(oauthUrl);
                session.setAttribute("weire_access_token", responseText);

                //weire广告展示页面处理
                this.adsList(response.getString("access_token"), response.getString("uid"), responseText);
            }else{
                return ERROR;
            }
        }
        return SUCCESS;
    }

    public void adsList(String access_token, String uid, String weire_access_token) {//weire广告展示页面

        if(access_token != null&&uid != null){
            //keywords 取得广告内容的参数
            String keywords = "";
            //category 取得广告内容的参数
            String categoryWords = "";

            String tagURL = "http://202.85.221.51:30080/Interestgraph/tag?vpuid=1109&token="+access_token+"&uid="+uid+"&weiresearch_"+weire_access_token;
                    //"http://localhost:20080/graph/tag?vpuid=1002&token="+access_token+"&uid="+uid+"&weiresearch_"+weire_access_token;

            String responseContent = this._sendHTTPGet(tagURL);
            Logger.getLogger(SinaLoginAction.class.getName()).log(Level.SEVERE, responseContent);
            if(responseContent == null){
            }
            try {
                JSONObject interests = new JSONObject(responseContent);
                //关键字信息
                if(interests.has("words")){
                    JSONArray words = interests.getJSONArray("words");
                    for(int i = 0; i < words.length(); i++){
                        JSONObject item = words.getJSONObject(i);
                        String word = item.getString("word");
                        keywords += word;
                        if(i != words.length()-1){
                            keywords += ",";
                        }
                    }
                }
                //分类信息
                if(interests.has("categories")){
                    JSONArray categories = interests.getJSONArray("categories");
                    for(int i = 0; i < categories.length(); i++){
                        JSONObject item = categories.getJSONObject(i);

                        String categoryI = item.getString("category");
                        if(categoryWords.length() > 0){
                            categoryWords += ",";
                        }
                        categoryWords += categoryI;
                    }
                }
                //suggestion 推荐
                String kw = "";
                if(categoryWords.isEmpty() || keywords.isEmpty()){
                    kw = categoryWords + keywords;
                }else {
                    kw = categoryWords + "," + keywords;
                }
                String keywordsURL = "http://202.85.221.51:30080/Interestgraph/resources/suggestions?weiresearch_"+weire_access_token+"&weiresearch_oauth_id=demo&keyword="+URLEncoder.encode(kw, "UTF-8");
                //String keywordsURL = "http://localhost:20080/graph/resources/suggestions?weiresearch_"+weire_access_token+"&weiresearch_oauth_id=test&keyword="+URLEncoder.encode(keywords, "UTF-8");
                String suggestions = this._sendHTTPGet(keywordsURL,"json");

                JSONObject suggestionObj = new JSONObject(suggestions);
                JSONArray suggestion = suggestionObj.getJSONArray("suggestion");
                //keywords ads'url map

                for(int i = 0; i < suggestion.length(); i++){
                    JSONObject item = suggestion.getJSONObject(i);
                    if(!item.has("picurl")||!item.has("position")){
                        continue;
                    }
                    String picurl = item.getString("picurl");
                    int position = item.getInt("position");
                    //this.adsURL.add(content);
                    switch (position) {
                        case 0: this.position0.add(picurl);break;
                        case 1: this.position1.add(picurl);break;
                        case 2: this.position2.add(picurl);break;
                        case 3: this.position3.add(picurl);break;
                        case 4: this.position4.add(picurl);break;
                        case 5: this.position5.add(picurl);
                        default: continue;
                    }
                }
            } catch (Exception ex) {
                Logger.getLogger(SinaLoginAction.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private String _sendHTTPPost(String urlStr) {
        URLConnection conn = null;
        try {
            URL url = new URL(urlStr);
            conn = url.openConnection();
            ((HttpURLConnection) conn).setRequestMethod("POST");

            conn.setRequestProperty("Content-Type", "text/html;charset=utf-8");
            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            rd.close();
            Logger.getLogger(SinaLoginAction.class.getName()).log(Level.INFO, sb.toString());
            return sb.toString();
        } catch (Exception ex) {
            Logger.getLogger(SinaLoginAction.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "{\"errorDescription\":\"登陆失败！\"}";
    }

    private String _sendHTTPGet(String urlStr) {
        URLConnection conn = null;
        try {
            URL url = new URL(urlStr);
            conn = url.openConnection();

            conn.setRequestProperty("Content-Type", "text/html;charset=utf-8");
            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            rd.close();
            Logger.getLogger(SinaLoginAction.class.getName()).log(Level.INFO, sb.toString());
            return sb.toString();
        } catch (Exception ex) {
            Logger.getLogger(SinaLoginAction.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "{\"errorDescription\":\"读取数据出错！\"}";
    }

    private String _sendHTTPGet(String urlStr, String type) {
        URLConnection conn = null;
        try {
            URL url = new URL(urlStr);
            conn = url.openConnection();

            if(type != null&&type.equalsIgnoreCase("json")){
                conn.setRequestProperty("Accept", "application/json");
            }
            conn.setRequestProperty("Content-Type", "text/html;charset=utf-8");
            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            rd.close();
            Logger.getLogger(SinaLoginAction.class.getName()).log(Level.INFO, sb.toString());
            return sb.toString();
        } catch (Exception ex) {
            Logger.getLogger(SinaLoginAction.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "{\"errorDescription\":\"读取数据出错！\"}";
    }
}
